import axios from "axios"

/**
 * 封装网络请求
 * 
 * @param {String} url 请求地址
 * @param {Object} data 请求体
 * @param {Object} headers 请求头
 * @param {Boolean} isJson 正文参数类型, 默认为json, 有时候服务器需要接收表单键值对形式的参数, 可以设置该参数为false
 * @param {Boolean} systemDealError 有些错误系统可以统一处理, 比如请求失败打印message
 * @param {String} method 请求类型
 */
const request = function (url, {params, data, headers, isJson, systemDealError, method}) {

    if (method == 'GET') {
        // GET请求无Content-Type
        headers = Object.assign(headers, {
            // 可以对token统一进行设置
            "token": "xxx"
        })
    } else {
        headers = Object.assign(headers, {
            // 可以对token统一进行设置
            "token": "xxx",
            // 设置Content-Type
            "Content-Type": isJson ? "application/json" : "application/x-www-form-urlencoded"
        })
    }

    return new Promise(resolve => {
        axios.request({
            url: url,
            method: method,
            params: params,
            data: data,
            headers: headers,
        }).then(res => {
            resolve(res);
        })
    })
}

const req = {
    /**
     * 根据网络请求类型对号入座, 这里需要注意的是get请求的data叫做parameters
     * 改名的目的就是为了要与data进行区分, data默认是json放在请求body中 {"id": "123"}
     * 而get请求没有body, 所以参数会拼接到url上 比如 www.baidu.com/?id=1
     */
    get: function (url, { params = {}, headers = {}, systemDealError = true }) {
        return request(url, {params: params, data: {}, headers: headers, isJson: false, systemDealError: systemDealError, method: 'GET'});
    },
    post: function (url, { params = {}, data = {}, headers = {}, isJson = true, systemDealError = true }) {
        return request(url, {params: params, data: data, headers: headers, isJson: isJson, systemDealError: systemDealError, method: 'POST'});
    },
    put: function (url, { params, data, headers = {}, isJson = true, systemDealError = true }) {
        return request(url, {params: params, data: data, headers: headers, isJson: isJson, systemDealError: systemDealError, method: 'PUT'});
    },
    delete: function (url, { params, data, headers = {}, isJson = true, systemDealError = true }) {
        return request(url, {params: params, data: data, headers: headers, isJson: isJson, systemDealError: systemDealError, method: 'DELETE'});
    }
}

const api = {
    api_testGet: process.env.VUE_APP_BASE_API + "/api/v1/test_get",
    api_testPostJson: process.env.VUE_APP_BASE_API + "/api/v1/test_post_json",
    api_testPostWWW: process.env.VUE_APP_BASE_API + "/api/v1/test_post_www"
}

export {
    req,
    api
}